package com.takeaway.servlet.filter;

import com.takeaway.const_.Const;
import com.takeaway.pojo.Shop;
import com.takeaway.pojo.User;
import com.takeaway.service.serviceimpl.ShopServiceImpl;
import com.takeaway.service.serviceinterface.ShopService;
import com.takeaway.utils.AgentManage;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 后台赖骏
 */
@WebFilter(urlPatterns = {"/jsp/ShopManage.jsp","/jsp/MenuManage.jsp","/business/checkShop",})
public class ShopManageFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        ShopService shopService = new ShopServiceImpl();
        AgentManage agentManage = new AgentManage(shopService);
        User user = (User)req.getSession().getAttribute("user");
        ShopService agent = (ShopService)agentManage.getAgent();
        try {
            Object[] objects = agent.checkShop(user.getId());
            Shop shop = (Shop) objects[0];
            if (shop.getShopCode()==1){
                filterChain.doFilter(req,resp);
            }
            else {
                req.setAttribute("msg", Const.MANAGE_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {

    }
}
